package argo.hot100.linklist;

public class RemoveNthFromEnd {


    public ListNode removeNthFromEnd(ListNode head, int n) {

        if (head.next == null && n == 1) {
            return null;
        }

        ListNode p = new ListNode(-1), p1 = head, p2 = head;
        p.next = head;
        while (n > 0 && p1.next != null) {
            n--;
            p1 = p1.next;
        }
        //if n>0, means remove first item
        if (n > 0) {
            p.next = p2.next;
        }

        while (p1.next != null) {
            p1 = p1.next;
            p2 = p2.next;
        }

        if (p2.next.next == null) {
            p2.next = null;
        } else {
            p2.next = p2.next.next;
        }


        return p.next;


    }


}
